package com.itheima.controller;


import com.itheima.common.CommonResult;
import com.itheima.common.PageInfo;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeeService;
import com.itheima.vo.EmployeeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/employee")
public class EmployeeController {


    //    @Autowired 按类型    要配合@Qualifier;    @Resource   按名称
    @Autowired
    private EmployeeService employeeService;


    //登录
    @PostMapping("/login")
    public CommonResult login(@RequestBody Employee employee) {

        EmployeeVo employeeVo = employeeService.login(employee.getUsername(), employee.getPassword());

        if (employeeVo == null) {
            return CommonResult.error("用户名或者密码错误");
        }

        return CommonResult.success(employeeVo);
    }

    //清除token
    @PostMapping("/logout")
    public CommonResult logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");//拿到请求头
        if (!StringUtils.hasText(token)) {
            return CommonResult.error("NOTLOGIN");
        }
        employeeService.clearToken(token);
        return CommonResult.success("退出登录成功");
    }


    //增加员工
    @PostMapping
    public CommonResult add(@RequestBody Employee employee) {

        boolean res = employeeService.addEmployee(employee);

        if (!res) {
            return CommonResult.error("添加失败");
        }


        return CommonResult.success("新增员工成功");
    }

    //根据Id查询
    @GetMapping("/{id}")
    public CommonResult getById(@PathVariable("id") String id) {
        return CommonResult.success(employeeService.getById(id));
    }

    //分页查询
    @GetMapping("/page")   //name判断了为空的情况，其他为空情况没判断，因此设置一个默认值@RequestParam
    public CommonResult page(String name,
                             //默认page为1
                             @RequestParam(defaultValue = "1") Integer page,
                             //默认pageSize为10
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Employee> page1 = employeeService.page(name, page, pageSize);
        return CommonResult.success(page1);
    }


    //修改员工
    @PutMapping("")
    public CommonResult updateEmployee(@RequestBody Employee employee) {
        boolean res = employeeService.updateEmployee(employee);
        if (!res) {
            return CommonResult.error("修改失败");
        }
        return CommonResult.success("修改成功");
    }
}
